<template>
  <!-- 关联小区 -->
  <view class="container">
    <view class="map-info">
      <view class="map-info-item">
        <view class="map-search">
          <input v-model="searchValue" type="text" class="u-text" placeholder="搜索小区名称" @input="handleInput" />
          <text class="u-btn" @tap="handleSearch">搜索</text>
        </view>
      </view>
      <view class="map-store" v-if="list.length > 0">
        <block v-for="item in list" :key="item.id">
          <view class="map-store_item" @tap="handleClick(item)">
            <view class="img">
              <image class="photo" :src="item.communityPhoto"></image>
            </view>
            <view class="info">
              <view class="name">{{ item.name }}</view>
              <view class="area">{{ item.sysAreaRegionalName ? item.sysAreaRegionalName : '' }}</view>
              <view class="txt">{{ item.communityAddress }}</view>
              <view class="distance">
                <!-- <image class="icon" :src="$pictureBaseUrl + 'static/imgs/icon-addre.png'" mode="widthFix" /> -->
                {{ item.distance }}
              </view>
              <view class="btn" :class="{ disabled: item.type !== 0 }">
                {{ item.type !== 0 ? '已关联' : '关联' }}
              </view>
            </view>
          </view>
        </block>
      </view>
    </view>
  </view>
</template>

<script>
import { getCommunityPage } from '@/api/community';
export default {
  data() {
    return {
      searchValue: '',
      paramsData: {
        page: 1,
        limit: 20,
        // lat: 0,
        // lng: 0,
        name: '', //小区名称
      },
      total: 0, //数据总条数
      list: [],
      inputTimer: null,
    };
  },
  computed: {
    // 总页数
    pageCount() {
      return this.total == 0 ? 0 : Math.ceil(this.total / this.paramsData.limit);
    },
  },
  onLoad() {
    this.init();
  },
  onReachBottom() {
    if (this.paramsData.page < this.pageCount) {
      this.paramsData.page++;
      this.getList();
    } else {
      uni.showToast({
        title: '没有更多数据了',
        icon: 'none',
        duration: 2000,
      });
    }
  },
  methods: {
    async init() {
      this.paramsData.teamLeaderId = uni.getStorageSync('teamLeaderId');
      // await this.getLocation(); //获取当前地理位置
      this.getList();
    },
    handleInput(e) {
      if (!!this.inputTimer) {
        clearTimeout(this.inputTimer);
        this.inputTimer = null;
      } else {
        this.inputTimer = setTimeout(() => {
          this.handleSearch();
          clearTimeout(this.inputTimer);
          this.inputTimer = null;
        }, 500);
      }
    },
    handleSearch() {
      this.paramsData.page = 1;
      this.paramsData.name = this.searchValue; //小区名称
      this.list = [];
      this.getList();
    },
    // 点击卡片行触发的事件
    handleClick(row) {
      if (row?.type === 1) return; //被当前登录的主理人关联

      const name = row.name;
      //被其他主理人关联
      if (row?.type === 2) {
        return uni.showToast({
          title: `小区【${name}】已被购买`,
          icon: 'none',
          duration: 1000,
        });
      }

      uni.showModal({
        title: '温馨提示',
        content: `是否关联【${name}】?`,
        success: res => {
          if (res.confirm) {
            //isCanBuy 当前登录的主理人是否可以购买该小区 1：可以 0：不能
            // if (row.isCanBuy === 1) {
            //   const communityId = row.id;
            //   order
            //     .getPayPreviewByTeamLeaderIdAndCommunityId({
            //       teamLeaderId: this.paramsData.teamLeaderId,
            //       communityId,
            //     })
            //     .then(res => {
            //       if (res.code === 0) {
            //         uni.navigateTo({
            //           url: `/pages/link_community/confirm_link_address?type=link_community&addIds=${communityId}`,
            //         });
            //       }
            //     });
            // } else {
            //   uni.showToast({
            //     title: '主理人只允许购买上级区域名下的小区',
            //     icon: 'none',
            //     duration: 1000,
            //   });
            // }
          }
        },
      });
    },
    getList() {
      const teamLeaderId = this.paramsData.teamLeaderId; //当前主理人id
      console.log('当前主理人id[teamLeaderId]:', teamLeaderId);
      getCommunityPage(this.paramsData).then(res => {
        console.log(res, 1213);
        // if (res.code === 1) {
        const list = res?.lists || [];
        list.forEach(item => {
          // 未关联小区为0
          // 当前登录主理人关联为1
          // 其他主理人关联为2
          item.type = !item?.teamLeaderId ? 0 : item?.teamLeaderId === teamLeaderId ? 1 : 2;
          const distance = item.distance ? Number(item.distance) : 0;
          item.distance = distance > 1000 ? `${(distance / 1000).toFixed(2)}千米` : `${Math.floor(distance)}米`;
        });
        this.list.push(...list);
        this.total = res?.count; // 更新总数据量
        // }
      });
    },
    // 获取当前地理位置
    getLocation() {
      return new Promise((resolve, reject) => {
        uni.getLocation({
          type: 'gcj02',
          isHighAccuracy: true,
          success: res => {
            console.log('getLocation：', res);
            this.$set(this.paramsData, 'lat', res?.lat);
            this.$set(this.paramsData, 'lng', res?.lng);
            resolve();
          },
          fail: err => {
            console.log('获取经纬度失败', err);
            reject();
          },
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  height: 100vh;
  background: #fff;
}

.map-info {
  padding: 30rpx 30rpx 10rpx;
  background-color: #fff;
  border-radius: 10rpx 10rpx 0 0;

  .map-info-item {
    position: fixed;
    top: 00rpx;
    left: 0;
    right: 0;
    z-index: 9;
    background-color: #fff;

    .map-search {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 20rpx;
      line-height: 60rpx;
      border: 1rpx solid #eee;
      border-radius: 50rpx;

      .u-text {
        flex: 1;
        line-height: 60rpx;
        padding-left: 30rpx;
        font-size: 26rpx;
        color: #333;
      }

      .u-btn {
        display: block;
        width: 120rpx;
        height: 60rpx;
        line-height: 60rpx;
        font-size: 26rpx;
        color: #5ff0a3;
        text-align: center;
      }
    }

    .map-addre {
      display: flex;
      justify-content: space-between;
      align-items: center;
      line-height: 60rpx;

      .now {
        flex: 1;
        font-size: 26rpx;
        color: #333;
      }

      .location {
        color: #666;
      }
    }
  }
}

.map-area {
  display: flex;
  justify-content: space-between;
  padding: 0;

  &_item {
    width: 47%;

    .area-select {
      width: 100%;
      height: 60rpx;
      line-height: 60rpx;
      font-size: 26rpx;
      color: rgb(0, 0, 0);
      text-align: center;
      border: 1rpx solid #eee;
      border-radius: 50rpx;
    }
  }
}

.map-store {
  max-height: 100%;
  margin-top: 16rpx;
  padding: 10rpx 10rpx 30px 10rpx;
  background-color: #f5f5f5;
  overflow-y: auto;
  margin-top: 120rpx;

  &_item {
    display: flex;
    position: relative;
    background-color: #fff;
    border: 1rpx solid #eee;
    padding: 10rpx;
    border-radius: 10rpx;

    &:not(:first-child) {
      margin-top: 10rpx;
    }

    .img {
      margin-right: 20rpx;
    }

    .photo {
      display: block;
      width: 140rpx;
      height: 140rpx;
      border-radius: 10rpx;
    }

    .info {
      flex: 1;
      min-width: 0;
      display: flex;
      flex-direction: column;
      justify-content: center;
    }

    .name {
      font-size: 28rpx;
      color: rgb(0, 0, 0);
    }

    .area {
      margin: 6rpx 0;
      font-size: 20rpx;
      color: #333;
      height: 20rpx;
    }

    .txt {
      font-size: 20rpx;
      color: #666;
    }

    .distance {
      display: flex;
      justify-content: flex-end;
      font-size: 22rpx;
      color: #333;

      .icon {
        display: block;
        width: 30rpx;
        height: 30rpx;
        margin-right: 6rpx;
      }
    }

    .current {
      position: absolute;
      top: 0;
      right: 0;
      height: 40rpx;
      padding: 0 16rpx;
      line-height: 40rpx;
      font-size: 24rpx;
      color: #5ff0a3;
      background-color: #333;
      border-radius: 0 10rpx 0 10rpx;
    }

    .btn {
      position: absolute;
      top: 50rpx;
      right: 20rpx;
      height: 50rpx;
      padding: 0 24rpx;
      line-height: 50rpx;
      font-size: 24rpx;
      color: #333;
      background-color: #a8fa9e;
      border-radius: 50rpx;

      &.disabled {
        background-color: #999;
        color: #fff;
      }
    }
  }
}
</style>
